package com.real.fact.web.customer.application;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.Validate;

import com.globant.katari.core.application.Command;
import com.real.fact.web.customer.domain.Customer;
import com.real.fact.web.customer.domain.CustomerRepository;
import com.real.fact.web.sale.domain.Sale;
import com.real.fact.web.sale.domain.SalePayment;
import com.real.fact.web.sale.domain.SaleRepository;
import com.real.fact.web.sale.domain.Ticket;

public class ListAccountSummaryCommand implements Command<List<AccountSummaryDTO>> {

  private final CustomerRepository customerRepository;
  
  private final SaleRepository salesRepository;

  private final Map<String, String> ticketTypes;
  
  private String ticketTypeSelected = Ticket.NONE.toString();

  private long customerId;

  public ListAccountSummaryCommand(final CustomerRepository theCustomerRepository,
      final SaleRepository theSalesRepository) {
    Validate.notNull(theCustomerRepository);
    Validate.notNull(theSalesRepository);
    customerRepository = theCustomerRepository;
    salesRepository = theSalesRepository;
    ticketTypes = new HashMap<String, String>();
    ticketTypes.put(Ticket.A.toString(), "Factura A");
    ticketTypes.put(Ticket.B.toString(), "Factura B");
    ticketTypes.put(Ticket.NONE.toString(), "N/A");
  }

  public long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(long customerId) {
    this.customerId = customerId;
  }

  public List<AccountSummaryDTO> execute() {
    List<Sale> sales = salesRepository.getSalesByCustomer(customerRepository.findById(customerId));
    List<AccountSummaryDTO> result = new ArrayList<AccountSummaryDTO>();
    for (Sale sale : sales) {
      float debt = calculateDebt(sale);
      if (debt > 0) {
        AccountSummaryDTO item = new AccountSummaryDTO(sale.getId(),
            sale.getDate(), sale.getTotal(), sale.getTotal() - debt, debt);
        result.add(item);
      }
    }
    return result;
  }

  private float calculateDebt(Sale sale) {
    List<SalePayment> payments = sale.getPayments();
    float payed = 0;
    float total = sale.getTotal();
    for (SalePayment payment : payments) {
      payed += payment.getAmount();      
    }
    return total - payed;
  }

  public String getTicketTypeSelected() {
    return ticketTypeSelected;
  }

  public void setTicketTypeSelected(String ticketTypeSelected) {
    this.ticketTypeSelected = ticketTypeSelected;
  }

  public Map<String, String> getTicketTypes() {
    return ticketTypes;
  }

  public Customer getCustomer() {
    return customerRepository.findById(customerId);
  }
}
